package com.qingcheng.service.impl;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qingcheng.dao.AdminMapper;
import com.qingcheng.dao.RoleMapper;
import com.qingcheng.dao.UserRoleMapper;
import com.qingcheng.entity.PageResult;
import com.qingcheng.pojo.system.Admin;
import com.qingcheng.pojo.system.AdminAndRole;
import com.qingcheng.pojo.system.Role;
import com.qingcheng.pojo.system.UserRole;
import com.qingcheng.service.system.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service(interfaceClass = AdminService.class)
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private AdminService adminService;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RoleMapper roleMapper;


    /**
     * 返回全部记录
     * @return
     */
    public List<Admin> findAll() {
        return adminMapper.selectAll();
    }

    /**
     * 分页查询
     * @param page 页码
     * @param size 每页记录数
     * @return 分页结果
     */
    public PageResult<Admin> findPage(int page, int size) {
        PageHelper.startPage(page,size);
        Page<Admin> admins = (Page<Admin>) adminMapper.selectAll();
        return new PageResult<Admin>(admins.getTotal(),admins.getResult());
    }

    /**
     * 条件查询
     * @param searchMap 查询条件
     * @return
     */
    public List<Admin> findList(Map<String, Object> searchMap) {
        Example example = createExample(searchMap);
        return adminMapper.selectByExample(example);
    }

    /**
     * 分页+条件查询
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    public PageResult<Admin> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page,size);
        Example example = createExample(searchMap);
        Page<Admin> admins = (Page<Admin>) adminMapper.selectByExample(example);
        return new PageResult<Admin>(admins.getTotal(),admins.getResult());
    }

    /**
     * 根据Id查询
     * @param id
     * @return
     */
    public AdminAndRole findById(Integer id) {
        //创建组合实体类对象，获取角色id集合
        AdminAndRole adminAndRole = new AdminAndRole();
        Admin admin = adminMapper.selectByPrimaryKey(id);

        //中间表对象
        UserRole userRole = new UserRole();
        //角色对象
        Role role = new Role();
        userRole.setAdminId(id);

        List<UserRole> userRoleList = userRoleMapper.select(userRole);
        ArrayList<Role> list = new ArrayList();
        for (UserRole userRole1 : userRoleList) {

            Role role1 = roleMapper.selectByPrimaryKey(userRole1.getRoleId());

        list.add(role1);
        }
        adminAndRole.setAdmin(admin);
        adminAndRole.setRoleList(list);

        return adminAndRole;


    }

    /**
     *修改过的添加
     *
     * @param adminAndRole
     */
    @Transactional
    public void add(AdminAndRole adminAndRole) {
        //取出管理员实体保存
        Admin admin = adminAndRole.getAdmin();
        admin.setPassword(BCrypt.hashpw(admin.getPassword(), BCrypt.gensalt()));//加密
        admin.setLoginName(admin.getLoginName());
        admin.setStatus("1");
        admin.setId(null);
        adminMapper.insert(admin);
//取出角色ID集合
        List<Role> roleList = adminAndRole.getRoleList();
        List<Integer> roleIds = roleList.stream().map(Role::getId).collect(Collectors.toList());
        //循环添加到管理员 角色中间表。
        for (Integer roleId : roleIds) {
            UserRole userRole = new UserRole();
            userRole.setAdminId(admin.getId());
            userRole.setRoleId(roleId);
            userRoleMapper.insert(userRole);
        }

    }





    /**
     * 修改
     * @param
     */
    //原来的修改方法
//    public void update(Admin admin) {
//        adminMapper.updateByPrimaryKeySelective(admin);
//    }
    /*修改版*/
    public void update(AdminAndRole adminAndRole) {

        Admin admin = adminAndRole.getAdmin();
        //加个判断
           if(!StringUtils.isEmpty(admin.getPassword())){
               String s = BCrypt.hashpw(admin.getPassword(), BCrypt.gensalt());//加密
               admin.setPassword(s);
           }
          /*中间表对象*/
        UserRole userRole = new UserRole();
        userRole.setAdminId(admin.getId());
        userRoleMapper.delete(userRole);
        //又创建一个中间表对象
        List<Role> roleList = adminAndRole.getRoleList();
        //循环添加到中间表
        for (Role role3 : roleList) {
            userRole.setRoleId(role3.getId());
            userRoleMapper.insert(userRole);
        }

        adminMapper.updateByPrimaryKeySelective(admin);

    }

    /**
     *  删除
     * @param id
     */
    public void delete(Integer id) {
        adminMapper.deleteByPrimaryKey(id);
    }

    /**
     *比较
     * @param searchMap
     */
    public void updatePassword(Map<String, Object> searchMap) {
       String loginName = (String) searchMap.get("loginName");
       String password = (String) searchMap.get("password");

        String newpassword = (String) searchMap.get("newpassword");
        Example example = new Example(Admin.class);

        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("loginName",loginName);
        Admin admin = adminMapper.selectOneByExample(example);

        if(BCrypt.checkpw(password,admin.getPassword())){
            String hashpw = BCrypt.hashpw(newpassword, BCrypt.gensalt());
            admin.setPassword(hashpw);
        }
        adminMapper.updateByPrimaryKeySelective(admin);

    }







    /**
     * 构建查询条件
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap){
        Example example=new Example(Admin.class);
        Example.Criteria criteria = example.createCriteria();
        if(searchMap!=null){
            // 用户名
            if(searchMap.get("loginName")!=null && !"".equals(searchMap.get("loginName"))){
                //criteria.andLike("loginName","%"+searchMap.get("loginName")+"%");
                criteria.andEqualTo("loginName",searchMap.get("loginName"));
            }
            // 密码
            if(searchMap.get("password")!=null && !"".equals(searchMap.get("password"))){
                criteria.andLike("password","%"+searchMap.get("password")+"%");
            }
            // 状态
            if(searchMap.get("status")!=null && !"".equals(searchMap.get("status"))){
                criteria.andEqualTo("status",searchMap.get("status"));
            }
            // id
            if(searchMap.get("id")!=null ){
                criteria.andEqualTo("id",searchMap.get("id"));
            }

        }
        return example;
    }

}
